<template>
  <!-- HTML -->
		<!--view>
			<image :src="srcstr" class="item-icon" 
			mode="" @tap="fanhui"></image>
		</view-->
      <mumu-get-qrcode ref="child" @success='qrcodeSucess' @error="qrcodeError"></mumu-get-qrcode>
</template>

<script>
// js
import mumuGetQrcode from '@/uni_modules/mumu-getQrcode/components/mumu-getQrcode/mumu-getQrcode.vue'
// 嫌路径长的话可以单独复制出来
export default {
	data() {
		return {
			mytype:'asset',
			myDocumentId:'',
			editDocumentId:'',
			continue:true,// false 监听一次   true 持续监听
			srcstr:'../../static/images/fanhui.png'
		};
	},
	components: {
		mumuGetQrcode
	},
	onLoad(params) {
		this.mytype=uni.getStorageSync('scanmytype');
		
		//console.log("来了");
		this.editDocumentId=params.editDocumentId;
	
	},
	methods: {
		qrcodeSucess(newdata) {
			this.mytype=uni.getStorageSync('scanmytype');
			const innerAudioContext = uni.createInnerAudioContext();
			innerAudioContext.autoplay = true;
			innerAudioContext.src = '../../static/MP3/5358.mp3';
			innerAudioContext.onPlay(() => {
			  console.log('开始播放');
			});
			innerAudioContext.onError((res) => {
			  console.log(res.errMsg);
			  console.log(res.errCode);
			});
			let data=JSON.parse(newdata);
	
			
			console.log(data.唯一标识);
			if(data.唯一标识!=undefined){
				//uni.navigateTo({
				//url: '../asset/asset?Id=' +mymodel.唯一标识+'&Type=2',
				//});
				console.log(this.mytype);
				if(this.mytype=='assetupload'){
					var toastMsg=null;
					this.request_tool({
						url:'/app/v1/document-detail/findByAssetId/'+data.唯一标识,
						type:'POST',
						data:{}
					}).then(res => {
						console.log(res);
						if(res.data.code=="2000"){
							if(res.data.map.document.status=="preparing" || res.data.map.document.status=="prepared"){
								uni.navigateTo({
									url: '../asset/assetedit?Type=2&AssetCode=' + data.资产编码,
								});
							}else{
								toastMsg =data.资产编码+"所属单据"+res.data.map.document.code+"单据状态不是制单中，不能再拍照";
							}
						}else{
							toastMsg =res.data.msg;
						}
					}).catch(err => {
						toastMsg='网络开小差了，请稍后重试!';
					}).finally(()=>{
						if(toastMsg){
							uni.showToast({
								icon: 'none',
								title: toastMsg
							});
							setTimeout(()=>{
								uni.navigateTo({
									url: '../home/scan-stock',
								});	
							},2000);
						}
					});
				}else if(this.mytype=='asset'){
					var toastMsg = null;
					this.request_tool({
						url:'/app/v1/asset/findByAssetCode/'+data.资产编码,
						type:'POST',
						data:{}
					}).then(res => {
						if(res.data.code="2000"){
							if(res.data.data){
								uni.setStorageSync("homeassets","1");
								uni.navigateTo({
									url: '../asset/asset?Type=2&AssetCode=' + data.资产编码,
								});
							}else{
								toastMsg ='资产'+data.资产编码+'尚未完成入库';
							}
						}else{
							toastMsg =res.data.msg;
						}
					}).catch(err => {
						toastMsg='网络开小差了，请稍后重试!';
					}).finally(()=>{
						if(toastMsg){
							uni.showToast({
								icon: 'none',
								title: toastMsg
							});
							setTimeout(()=>{
								uni.navigateTo({
									url: '../home/scan-stock',
								});	
							},2000);
						}
					});
				}else if(this.mytype=='edit'){
					console.log(this.editDocumentId);
					var added =[];
					added.push(data.唯一标识);
					uni.request({
						url: uni.getStorageSync("localurl")+'/Documents/Asset_Change_Add_Detail_Save',
						data: {
							_Added: added,
							_r: "dde7a3ef-2a1a-4494-880f-7c4f56dd0f9e",
							_Removed: [],
							DocumentId:this.editDocumentId
						},
												method:"POST",
						success: (res) => {
							console.log(res);
							if (res.data.successed == true) {
								uni.navigateTo({
									url: '../asset/documentedit?act=edit&document_id=' + this.editDocumentId,
								});
							}else{
								uni.navigateTo({
									url: '../asset/documentedit?act=edit&document_id=' + this.editDocumentId,
								});
							}
						},
						fail: () => {
							//  请求失败,隐藏加载状态
							uni.navigateTo({
								url: '../asset/documentedit?act=edit&document_id=' + this.editDocumentId,
							});
						}
					});
					
				}else{
					const myDocumentId = uni.getStorageSync('DocumentId');
					const userinfo = uni.getStorageSync("userInfo");
					let querydata={
							"pageSize": 10,
							"current": 1,
							manageUser:JSON.parse(userinfo).id,
							queryDocumentIds:[myDocumentId],
							assetCode:data.资产编码,
						};
						
					console.log(querydata);
					var toastMsg = null;
					this.requeststo_tool({
						url:'/app/v1/assetCheck/getCheckDetailPageData',
						type:'POST', 
						data:querydata
					}).then(res2 => {
						if (res2.data.code == 2000) {
							let list=res2.data.data.records;
							if(list.length>0){
								uni.navigateTo({
									url: '../stock/StockDocumentAsset?AssetCode=' + data.资产编码 + '&type=1',
								});
							}else{
								toastMsg = "扫描资产不在盘点单内";
							}
						}else{
							toastMsg = res2.data.msg;
						}
					}).catch(err => {
						toastMsg="网络开小差了，请稍后重试!";
					}).finally(()=>{
						if(toastMsg){
							uni.showToast({
								icon: 'none',
								title: toastMsg
							});
							setTimeout(()=>{
								uni.navigateTo({
									url: '../home/scan-stock',
								});	
							},2000);
						}
					});
				}
			}else{
				var toastMsg ='无法识别二维码';
				if(toastMsg){
					uni.showToast({
						icon: 'none',
						title: toastMsg
					});
					setTimeout(()=>{
						uni.navigateTo({
							url: '../home/scan-stock',
						});	
					},2000);
				}
			}
		},
		  qrcodeError(err) {
			console.log(err)
			uni.showModal({
			  title: '摄像头授权失败',
			  content: '摄像头授权失败，请检测当前浏览器是否有摄像头权限。',
			  success: () => {
				//uni.navigateBack({})
			  }
			})
		  },
			request_tool(options){
			 // 在这里可以对请求头进行一些设置
			 let baseUrl = uni.getStorageSync("localurl"); 
			 let userInfo = uni.getStorageSync("userInfo");
			 if (userInfo) {
			 	options.data['userLevelCode'] =JSON.parse(userInfo).levelCode;
			 	options.data['loginUserId'] = JSON.parse(userInfo).id;
			 }
			 let userDept = uni.getStorageSync("userDept");
			// console.log(userDept);
			 if (userDept) {
			 	options.data['loginUserDeptLevelCode'] = userDept.levelCode;
			 	options.data['loginUserDeptId'] = userDept.id;
			 }
			 let currentRole = uni.getStorageSync("userRoles");
			  //console.log(currentRole);
			 if (currentRole) {
			 	options.data['roleLevelCode'] = currentRole[0].levelCode;
			 	options.data['roleId'] = currentRole[0].id;
			 }
			 let userReadDeptIds = uni.getStorageSync("userReadDeptIds");
			 
			 if (userReadDeptIds) {
			 	options.data['deptIds'] =userReadDeptIds;
			 }
			  options.header = {
			      'Content-Type':'application/json',
			      Authorization: uni.getStorageSync("authorization")
			 }
			
			    return new Promise((resolve, reject) => {
			        uni.request({
			            url: baseUrl + options.url || '',
			            method: options.type || 'POST',
			            data: options.data || {},
			            header: options.header || {}      
			        }).then(data => {
			            let [err, res] = data;
						if(res.data.code==5001 || res.data.code==5002 ||
						res.data.code==5003 || res.data.code==5004){
							uni.removeStorageSync("LoginName");
							uni.removeStorageSync("userInfo");
							uni.removeStorageSync("authorization");
							uni.removeStorageSync("userToken")
							uni.removeStorageSync("userRoles");
							uni.removeStorageSync("userDept");
							uni.removeStorageSync("userReadDeptIds");
							uni.removeStorageSync("managePositionIds");
							uni.removeStorageSync("ASSETCODE");
							uni.navigateTo({
								url: '../login/login',
							});
						}
			            resolve(res);
			        }).catch(error => {
			            reject(error)
			        })
			    });
			},
			requeststo_tool(options){
			 // 在这里可以对请求头进行一些设置
			 let baseUrl = uni.getStorageSync("localurl");
			 			
			  options.header = {
			      'Content-Type':'application/json',
			      Authorization: uni.getStorageSync("authorization")
			 }
			 			
			    return new Promise((resolve, reject) => {
			        uni.request({
			            url: baseUrl + options.url || '',
			            method: options.type || 'POST',
			            data: options.data || {},
			            header: options.header || {}      
			        }).then(data => {
			            let [err, res] = data;        
			            resolve(res);
			        }).catch(error => {
			            reject(error)
			        })
			    });
			},
			fanhui(){
				 uni.navigateBack({
				        delta: 1 // 默认值是1，表示返回的页面层数
				      });
			}
	},
	onBackPress() {
		// #ifdef APP-PLUS
		// 点击返回时退出全屏
		barcode.close();
		//plus.navigator.setFullscreen(false);
		// #endif
		if(this.mytype=='asset'){
			console.log(11);
		uni.setStorageSync('homebackDate', 0);
		uni.setStorageSync('setStatusIndexFunc', 0);
		}
	}
}
</script>
